package com.jilian.mydemo.modul.shop.ui;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.widget.RxTextView;
import com.jilian.mydemo.MyApplication;
import com.jilian.mydemo.R;
import com.jilian.mydemo.base.BaseActivity;
import com.jilian.mydemo.base.BaseDto;
import com.jilian.mydemo.common.dto.BannerDto;
import com.jilian.mydemo.common.dto.BannerListDto;
import com.jilian.mydemo.common.dto.GoodsTypeDto;
import com.jilian.mydemo.common.dto.ProductDto;
import com.jilian.mydemo.common.dto.ProductListDto;
import com.jilian.mydemo.common.vo.BannerVo;
import com.jilian.mydemo.factory.Factoty;
import com.jilian.mydemo.listener.CustomItemClickListener;
import com.jilian.mydemo.listener.ViewPagerItemClickListener;
import com.jilian.mydemo.modul.main.adapter.BananerPagerAdapter;
import com.jilian.mydemo.modul.main.ui.OneFragment;
import com.jilian.mydemo.modul.order.ui.WebViewActivity;
import com.jilian.mydemo.modul.shop.adapter.AccessoriesShopAdapter;
import com.jilian.mydemo.modul.shop.adapter.TypeTopAdapter;
import com.jilian.mydemo.modul.user.viewmodel.UserViewModel;
import com.jilian.mydemo.utils.DisplayUtil;
import com.jilian.mydemo.utils.EmptyUtils;
import com.jilian.mydemo.utils.ToastUitl;
import com.jilian.mydemo.views.CornerView;
import com.jilian.mydemo.views.RecyclerViewSpacesItemDecoration;
import com.jilian.mydemo.views.ViewPagerIndicator;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 配件商城
 */
public class AccessoriesShopActivity extends BaseActivity implements CustomItemClickListener, ViewPagerItemClickListener, TypeTopAdapter.TypeTopListener {
    private EditText etSearch;
    private ImageView ivSearch;
    private CornerView cornerView;
    private ViewPager viewPager;
    private LinearLayout llIndcator;
    private RecyclerView recyclerview;
    private GridLayoutManager gridLayoutManager;
    private AccessoriesShopAdapter accessoriesShopAdapter;
    private List<ProductDto> datas;
    private List<BannerDto> list;
    private BananerPagerAdapter bananerPagerAdapter;
    private SmartRefreshLayout srHasData;
    private SmartRefreshLayout srNoData;
    private UserViewModel userViewModel;
    private RecyclerView rvTop;
    private LinearLayoutManager lm_top;
    private TypeTopAdapter typeTopAdapter;
    private List<GoodsTypeDto> typeDtos;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    @Override
    protected void createViewModel() {
        userViewModel = Factoty.getViewModel(UserViewModel.class, this);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_accessoriesshop;
    }

    @Override
    public void initView() {


        setNormalTitle("配件商城", v -> finish());
        srHasData = (SmartRefreshLayout) findViewById(R.id.sr_has_data);
        srNoData = (SmartRefreshLayout) findViewById(R.id.sr_no_data);
        srNoData.setEnableLoadMore(false);
        etSearch = (EditText) findViewById(R.id.et_search);
        ivSearch = (ImageView) findViewById(R.id.iv_search);
        cornerView = (CornerView) findViewById(R.id.cornerView);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        llIndcator = (LinearLayout) findViewById(R.id.ll_indcator);
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(RecyclerViewSpacesItemDecoration.RIGHT_DECORATION, DisplayUtil.dip2px(this, 5));//右间距
        map.put(RecyclerViewSpacesItemDecoration.BOTTOM_DECORATION, DisplayUtil.dip2px(this, 5));//下间距
        recyclerview.addItemDecoration(new RecyclerViewSpacesItemDecoration(map));
        cornerView.setCorner(0);
        gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerview.setLayoutManager(gridLayoutManager);
        datas = new ArrayList<>();
        accessoriesShopAdapter = new AccessoriesShopAdapter(this, datas, this);
        recyclerview.setAdapter(accessoriesShopAdapter);
        //
        rvTop = (RecyclerView) findViewById(R.id.rv_top);
        lm_top = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvTop.setLayoutManager(lm_top);
        typeDtos = new ArrayList<>();
        typeTopAdapter = new TypeTopAdapter(this, typeDtos, this);
        rvTop.setAdapter(typeTopAdapter);

    }

    private Integer pageNum = 1;//
    private Integer pageSize = 20;//

    /**
     * 获取商品类型
     */
    private void queryProductTypes() {
        Factoty.getViewModel(UserViewModel.class, AccessoriesShopActivity.this).queryProductTypes();
        Factoty.getViewModel(UserViewModel.class, AccessoriesShopActivity.this).getGoodsTypeDtoliveData().observe(this, new Observer<BaseDto<List<GoodsTypeDto>>>() {
            @Override
            public void onChanged(@Nullable BaseDto<List<GoodsTypeDto>> listBaseDto) {
                hideLoadingDialog();
                if (listBaseDto.isSuccess()) {
                    if (EmptyUtils.isNotEmpty(listBaseDto.getData())) {
                        typeDtos.clear();
                        listBaseDto.getData().get(0).setSelected(true);
                        typeDtos.addAll(listBaseDto.getData());
                        typeTopAdapter.notifyDataSetChanged();
                        getAppProductList();
                    }
                } else {
                    ToastUitl.showImageToastTips(listBaseDto.getMsg());
                }


            }
        });
    }


    /**
     * 获取产品列表
     */
    private void getAppProductList() {
        Factoty.getViewModel(UserViewModel.class, AccessoriesShopActivity.this).getAppProductList(pageNum, pageSize, etSearch.getText().toString(), getGoodsType());
        Factoty.getViewModel(UserViewModel.class, AccessoriesShopActivity.this).getProductliveData().observe(this, new Observer<BaseDto<ProductListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<ProductListDto> listBaseDto) {
                hideLoadingDialog();
                srNoData.finishRefresh();
                srHasData.finishRefresh();
                srHasData.finishLoadMore();
                //有数据
                if (listBaseDto.isSuccess() && EmptyUtils.isNotEmpty(listBaseDto.getData().getList())) {
                    srNoData.setVisibility(View.GONE);
                    srHasData.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        datas.clear();
                    }
                    datas.addAll(listBaseDto.getData().getList());
                    accessoriesShopAdapter.notifyDataSetChanged();
                } else {
                    //说明是上拉加载
                    if (pageNum > 1) {
                        pageNum--;
                    } else {
                        //第一次就没数据
                        srNoData.setVisibility(View.VISIBLE);
                        srHasData.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    /**
     * 初始化banner
     */
    private void initBanner() {

        viewPager.addOnPageChangeListener(new ViewPagerIndicator(this, viewPager, llIndcator, list.size()));
        bananerPagerAdapter = new BananerPagerAdapter(this, list, this);
        viewPager.setAdapter(bananerPagerAdapter);
    }

    @Override
    public void initData() {
        showLoadingDialog();
        getBanner();
        queryProductTypes();
    }

    /**
     * 获取广告banner
     */
    private void getBanner() {
        BannerVo vo = new BannerVo();
        vo.setLocation(1);
        userViewModel.getAppAdList(vo);
        userViewModel.getBannerLiveData().observe(this, new Observer<BaseDto<BannerListDto>>() {
            @Override
            public void onChanged(@Nullable BaseDto<BannerListDto> dto) {
                if (dto.isSuccess() && dto.getData() != null && EmptyUtils.isNotEmpty(dto.getData().getList())) {
                    list = new ArrayList<>();
                    list.addAll(dto.getData().getList());
                    initBanner();
                }
            }
        });
    }

    @Override
    public void initListener() {
        //RxJava过滤操作符的应用-实时搜索功能
        RxTextView.textChanges(etSearch)
                //监听输入完200毫秒之后发送事件
                .debounce(200, TimeUnit.MILLISECONDS)
                //跳过输入框EditText 初始化的的时候产生的事件。
                .skip(1)
                //把观察者切换到UI线程
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new rx.Observer<CharSequence>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e.toString());
                    }

                    @Override
                    public void onNext(CharSequence charSequence) {
                        Log.e(TAG, "onNext: " + charSequence.toString());
                        pageNum = 1;
                        getAppProductList();


                    }
                });
        srHasData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                getAppProductList();
            }
        });
        srHasData.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                getAppProductList();
            }
        });
        srNoData.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                getAppProductList();
            }
        });
//        tvOne.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                tvOne.setTextColor(getResources().getColor(R.color.color_main_title));
//                tvTwo.setTextColor(getResources().getColor(R.color.color_hint));
//                rlOne.setVisibility(View.VISIBLE);
//                rlTwo.setVisibility(View.INVISIBLE);
//
//            }
//        });
//        tvTwo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                tvOne.setTextColor(getResources().getColor(R.color.color_hint));
//                tvTwo.setTextColor(getResources().getColor(R.color.color_main_title));
//                rlOne.setVisibility(View.INVISIBLE);
//                rlTwo.setVisibility(View.VISIBLE);
//            }
//        });
    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(this, GoodDetailActivity.class);
        //1 首頁進來 //2 为添加配件 跳到 该界面
        intent.putExtra("param", getIntent().getIntExtra("param", 1));
        intent.putExtra("id", String.valueOf(datas.get(position).getId()));
        startActivity(intent);
    }

    @Override
    public void onViewPageItemClick(View view, int position) {
        String url = list.get(position).getAdUrl();
        if(TextUtils.isEmpty(url)){
            return;
        }
        Intent intent = new Intent(this,WebViewActivity.class);
        intent.putExtra("linkUrl",url);
        startActivity(intent);

    }

    @Override
    public void oneTypeClick(View view, int position) {
        for (int i = 0; i < typeDtos.size(); i++) {
            if (i == position) {
                typeDtos.get(i).setSelected(true);
            } else {
                typeDtos.get(i).setSelected(false);
            }
        }
        typeTopAdapter.notifyDataSetChanged();
        getAppProductList();
    }

    /**
     * 获取类型
     *
     * @return
     */
    private String getGoodsType() {
        for (int i = 0; i < typeDtos.size(); i++) {
            if (typeDtos.get(i).isSelected()) {
                return typeDtos.get(i).getCode();
            }
        }
        return null;
    }
}
